<template>
    <v-container fluid>
        <v-data-table
                :headers="headers"
                :items="users"
                :options.sync="options"
                :server-items-length="totalUsers"
                :loading="loading"
                :items-per-page="5"
                class="elevation-1">
            <template v-slot:top>
                <v-toolbar flat>
                    <!--starter 添加 修改表单 -->
                    <v-dialog
                            v-model="updateDialog"
                            max-width="500px">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn
                                    color="primary"
                                    dark
                                    class="mb-2"
                                    v-bind="attrs"
                                    v-on="on">
                                添加用户
                            </v-btn>
                        </template>
                        <v-card>
                            <v-card-title>
                                <span class="headline">{{ formTitle }}</span>
                            </v-card-title>

                            <v-card-text>
                                <v-container>
                                    <v-row>
                                        <v-col
                                                cols="2">
                                            <v-avatar color="grey lighten-3">
                                                <v-img v-if="editedItem.avatar || editedItem.avatar!==''" size="56"
                                                       :src="editedItem.avatar"></v-img>
                                                <v-icon v-else>
                                                    mdi-account
                                                </v-icon>
                                            </v-avatar>
                                        </v-col>
                                        <v-col
                                                cols="12"
                                                sm="6"
                                                md="4">
                                            <v-text-field
                                                    v-model="editedItem.nickname"
                                                    label="昵称"></v-text-field>
                                        </v-col>
                                        <v-col
                                                cols="12"
                                                sm="6"
                                                md="4">
                                            <v-text-field
                                                    v-model="editedItem.username"
                                                    label="账号"></v-text-field>
                                        </v-col>
                                        <v-col
                                                cols="12"
                                                sm="6"
                                                md="4"
                                                v-if="editedIndex === -1">
                                            <v-text-field
                                                    v-model="editedItem.password"
                                                    type="password"
                                                    label="密码"></v-text-field>
                                        </v-col>
                                        <v-col
                                                cols="12"
                                                sm="6"
                                                md="4">
                                            <v-select :items="sex"
                                                      label="性别"
                                                      item-text="value"
                                                      item-value="key"
                                                      v-model="editedItem.sex"/>
                                        </v-col>
                                        <v-col
                                                cols="12"
                                                sm="4">
                                            <v-dialog
                                                    ref="dateDialog"
                                                    v-model="datePickersDialog"
                                                    :return-value.sync="editedItem.birthday"
                                                    persistent
                                                    width="290px">
                                                <template v-slot:activator="{ on, attrs }">
                                                    <v-text-field
                                                            v-model="editedItem.birthday"
                                                            label="出生日期"
                                                            prepend-icon="mdi-calendar"
                                                            readonly
                                                            v-bind="attrs"
                                                            v-on="on"></v-text-field>
                                                </template>
                                                <v-date-picker
                                                        v-model="editedItem.birthday"
                                                        scrollable
                                                        locale="zh-cn"
                                                        :first-day-of-week="1">
                                                    <v-spacer></v-spacer>
                                                    <v-btn
                                                            text
                                                            color="primary"
                                                            @click="datePickersDialog = false">
                                                        Cancel
                                                    </v-btn>
                                                    <v-btn
                                                            text
                                                            color="primary"
                                                            @click="$refs.dateDialog.save(editedItem.birthday)">
                                                        OK
                                                    </v-btn>
                                                </v-date-picker>
                                            </v-dialog>
                                        </v-col>
                                        <v-col cols="12"
                                               sm="12"
                                               md="12">
                                            <v-autocomplete
                                                    v-model="roleIds"
                                                    :items="roles"
                                                    dense
                                                    chips
                                                    small-chips
                                                    item-value="id"
                                                    item-text="roleName"
                                                    label="角色"
                                                    multiple
                                            ></v-autocomplete>
                                        </v-col>
                                    </v-row>
                                </v-container>
                            </v-card-text>

                            <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn
                                        color="blue darken-1"
                                        text
                                        @click="close">
                                    Cancel
                                </v-btn>
                                <v-btn
                                        color="blue darken-1"
                                        text
                                        @click="save">
                                    Save
                                </v-btn>
                            </v-card-actions>
                        </v-card>
                    </v-dialog>
                    <!--end 添加 修改表单 -->
                    <v-spacer></v-spacer>
                    <v-text-field label="Search"
                                  hide-details
                                  v-model="search"
                                  style="max-width: 175px">
                        <v-btn slot="append-outer"
                               elevation="1"
                               class="mt-n2"
                               @click="searchAccount"
                               icon small fab>
                            <v-icon>
                                mdi-magnify
                            </v-icon>
                        </v-btn>
                    </v-text-field>
                    <v-dialog v-model="dialogDelete" max-width="500px">
                        <v-card>
                            <v-card-title class="headline">确定删除此条记录?</v-card-title>
                            <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
                                <v-btn color="blue darken-1" text @click="deleteItemConfirm">确定</v-btn>
                                <v-spacer></v-spacer>
                            </v-card-actions>
                        </v-card>
                    </v-dialog>
                </v-toolbar>
            </template>
            <template v-slot:item.actions="{ item }">
                <v-icon
                        small
                        class="mr-2"
                        @click="editItem(item)"
                >
                    mdi-pencil
                </v-icon>
                <v-icon
                        small
                        @click="deleteItem(item)"
                >
                    mdi-delete
                </v-icon>
            </template>
            <template v-slot:item.avatar="{ item }">
                <v-avatar size="20" v-if="item.avatar!==undefined">
                    <v-img :src="item.avatar"/>
                </v-avatar>
                <v-avatar size="20" v-else>
                    <v-icon>
                        mdi-account
                    </v-icon>
                </v-avatar>
            </template>
            <template v-slot:item.sex="{ item }">
                <v-chip dark v-if="item.sex===0" color="pink" text-color="white">
                    女
                </v-chip>
                <v-chip dark v-else color="blue" text-color="white">
                    男
                </v-chip>
            </template>
            <template v-slot:no-data>
                <v-btn
                        color="primary"
                        @click="initialize"
                >
                    Reset
                </v-btn>
            </template>
        </v-data-table>
    </v-container>
</template>

<script>
    export default {
        name: "userManage",
        data: () => ({
            search: '',
            totalUsers: 0,
            loading: true,
            options: {},
            headers: [,
                {
                    text: '名称',
                    value: 'nickname',
                    sortable: false,
                    align: 'center'
                },
                {
                    text: '头像',
                    value: 'avatar',
                    sortable: false,
                    align: 'center'
                },
                {
                    text: '性别',
                    value: 'sex',
                    align: 'center'
                },
                {
                    text: '出生日期',
                    value: 'birthday',
                    align: 'center'
                },
                {
                    text: '操作',
                    value: 'actions',
                    sortable: false,
                    align: 'center'
                },
            ],
            users: [],
            imgFile: {},
            editedIndex: -1,
            updateDialog: false,
            datePickersDialog: false,
            dialogDelete: false,
            sex: [
                {
                    key: -1,
                    value: '未知'
                },
                {
                    key: 0,
                    value: '女'
                }, {
                    key: 1,
                    value: '男'
                }
            ],
            roles: [],
            roleIds: [],
            editedItem: {
                id: '',
                username: '',
                password: '',
                nickname: '',
                avatar: '',
                sex: -1,
                birthday: ''
            },
            defaultItem: {
                sex: -1,
                birthday: new Date().toISOString().substr(0, 10),
            },
        }),

        computed: {
            formTitle() {
                return this.editedIndex === -1 ? '新增用户' : '修改用户'
            },
        },

        watch: {
            dialog(val) {
                val || this.close()
            },
            dialogDelete(val) {
                val || this.closeDelete()
            },
            options: {
                handler() {
                    // 监听改变发送请求(初始化options)
                    this.initialize();
                },
                deep: true,
            },
            file(val) {
                console.log(val);
            }
        },

        created() {

        },

        methods: {
            initialize() {
                // 加载User数据
                this.$axios.get("user/page", {
                    params: {
                        search: this.search,
                        page: this.options.page,
                        pageSize: this.options.itemsPerPage,
                        sortBy: this.options.sortBy,
                        desc: this.options.sortDesc
                    }
                }).then(response => {
                    let data = response.data;
                    this.users = data.items;
                    this.totalUsers = data.total;
                    this.loading = false;
                }).catch(error => {
                    console.log(error);
                })
                // 加载Roles数据
                if (this.roles.length === 0) {
                    this.$axios.get('role').then(
                        response => {
                            this.roles = response.data
                        }
                    ).catch(error => {
                        console.log(error)
                    })
                }
            },

            searchAccount() {
                this.initialize();
            },

            editItem(item) {
                this.editedIndex = this.users.indexOf(item);
                this.editedItem = Object.assign({}, item);
                this.updateDialog = true
                // 获取所属角色
                this.$axios.get("role/user/" + this.editedItem.id).then(response => {
                    this.roleIds = response.data
                }).catch(error => {
                    console.log(error)
                })
            },

            deleteItem(item) {
                this.editedIndex = this.users.indexOf(item)
                this.editedItem = Object.assign({}, item)
                this.dialogDelete = true
            },

            deleteItemConfirm() {
                // 删除
                // this.users.splice(this.editedIndex, 1)
                this.$axios.delete("user/" + this.users[this.editedIndex].id).then(response => {
                    this.initialize()
                }).catch(error => {
                    console.log(error);
                })
                this.closeDelete()
            },

            close() {
                this.roleIds = []
                this.updateDialog = false
                this.$nextTick(() => {
                    this.editedItem = Object.assign({}, this.defaultItem)
                    this.editedIndex = -1
                })
            },

            closeDelete() {
                this.dialogDelete = false
                this.$nextTick(() => {
                    this.editedItem = Object.assign({}, this.defaultItem)
                    this.editedIndex = -1
                })
            },

            save() {
                if (this.editedIndex > -1) {
                    // 修改
                    this.$axios.put("user", {
                        'id': this.editedItem.id,
                        'nickname': this.editedItem.nickname,
                        'username': this.editedItem.username,
                        'sex': this.editedItem.sex,
                        'birthday': this.editedItem.birthday,
                        'roleIds': this.roleIds
                    }).then(response => {
                        // Object.assign(this.users[this.editedIndex], this.editedItem);
                        this.initialize();
                        this.close()
                    }).catch(error => {
                        console.log(error);
                    });
                } else {
                    // 保存
                    this.$axios.post('user', {
                        'nickname': this.editedItem.nickname,
                        'username': this.editedItem.username,
                        'sex': this.editedItem.sex,
                        'birthday': this.editedItem.birthday,
                        'roleIds': this.roleIds
                    }).then(response => {
                        this.initialize()
                    }).catch(error => {
                        console.log(error);
                    }).finally(() => {
                        this.close()
                    });
                }
            },
        },
    }
</script>

<style scoped>

</style>